package preorder
import (
    "time"
	"strings"
	"errors"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

// 预约参数管理
type PreOrderOpt struct {
	PreOrderOptId  int64  `orm:"column(pre_order_opt_id);pk;auto" json:"pre_order_opt_id" form:"pre_order_opt_id"`
	PartnerId      int64  `orm:"column(partner_id);unique" json:"partner_id" form:"partner_id"`    
    StoreId        int64  `orm:"column(store_id)" json:"store_id" form:"store_id"`
	CanCancelDays  int    `orm:"column(can_cancel_days)" json:"can_cancel_days" form:"can_cancel_days"`     //可取消预约天数
	CanReserveDays int    `orm:"column(can_reserve_days)" json:"can_reserve_days" form:"can_reserve_days"`  //可预约天数
	AckMode        int    `orm:"column(ack_mode)" json:"ack_mode" form:"ack_mode"`                          //预约单确认方式
	IsNeedDeposit  bool `orm:"column(is_need_deposit);default(false)" json:"is_need_deposit" form:"is_need_deposit"` //需要定金?
	IsOpen         bool   `orm:"column(is_open);default(false)" json:"is_open" form:"is_open"`              //是否启用
	CreatedAt time.Time   `orm:"auto_now_add;column(created_at);type(datetime)" json:"created_at"`            //创建时间
	UpdatedAt time.Time   `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"`                //修改时间
}

func init() {
	orm.RegisterModel(new(PreOrderOpt))
}

func InitDefaultPreOrderOpt(partnerId, storeId int64)(err error) {
    if _, err = GetPreOrderOptByPartnerId(partnerId, storeId); err == orm.ErrNoRows {
	    preOrderOpt := new(PreOrderOpt)
		preOrderOpt.PartnerId = partnerId
		preOrderOpt.StoreId = storeId
		preOrderOpt.CanCancelDays = 2
		preOrderOpt.CanReserveDays = 7
		preOrderOpt.AckMode = 1
		preOrderOpt.IsNeedDeposit = false
		_, err = AddPreOrderOpt(preOrderOpt)
	}
	return
}

func AddPreOrderOpt(m *PreOrderOpt) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddMultiPreOrderOpts(list []*PreOrderOpt) (err error) {
	size := len(list)
	o := models.GetDefaultDB()
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}
	return
}

func GetPreOrderOptById(id int64) (v *PreOrderOpt, err error) {
	o := models.GetDefaultDB()
	v = &PreOrderOpt{PreOrderOptId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetPreOrderOptByPartnerId(partnerId, storeId int64) (v *PreOrderOpt, err error) {
	o := models.GetDefaultDB()
	v = &PreOrderOpt{PartnerId:partnerId, StoreId:storeId}
	if err = o.Read(v, "PartnerId", "StoreId"); err == nil {
		return v, nil
	}
	return nil, err
}


//查询所有餐桌
func GetAllPreOrderOpts(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*PreOrderOpt, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(PreOrderOpt))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	var lists []*PreOrderOpt
	qs = qs.OrderBy(sortFields...)
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}
func UpdatePreOrderOptById(m *PreOrderOpt, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := PreOrderOpt{PreOrderOptId: m.PreOrderOptId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}
func DeletePreOrderOptById(id int64) (err error) {
	o := models.GetDefaultDB()
	v := PreOrderOpt{PreOrderOptId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

func DeletePreOrderOptByPartnerId(partnerId, storeId int64) (err error) {
	o := models.GetDefaultDB()
	v := PreOrderOpt{PartnerId:partnerId, StoreId:storeId}
	if err = o.Read(&v, "PartnerId", "StoreId"); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
